<template>
<div>
      <!-- 搜索结果页-头部导航 -->
      <div class="search-result-container">
        <!-- 点击实现后退效果 -->
        <van-nav-bar
          title="搜索结果"
          left-arrow
          @click-left="$router.go(-1)"
          fixed
        />
      </div>
    <van-list
      v-model="loading"
      :finished="finished"
      finished-text="没有更多了"
      @load="onLoad"
      :immediate-check="false"
    >
      <!-- 文章搜索结果列表 -->
      <div v-for="article in articleList" :key="article.art_id">
        <ArticlesListItem :articles="article" :showIcon="false" @click.native="articleDetail(article.art_id)"/>
      </div>
    </van-list>
    </div>
</template>

<script>
import { searchResultAPI } from '@/api/index'
import ArticlesListItem from '@/components/ArticlesListItem.vue'
import { timeAgo } from '@/utils/date'
export default {
  name: 'SearchResult',
  components: { ArticlesListItem },
  props: ['kw'],
  data () {
    return {
      articleList: [],
      finished: false, // 是否全部加载完成
      loading: false, // 加载状态
      page: 1 // 页码
    }
  },
  methods: {
    formatTime: timeAgo,
    // 获取搜索结果
    async getSearchResult () {
      const res = await searchResultAPI({
        q: this.kw,
        page: this.page
      })
      if (res.data.data.results.length === 0) {
        // 加载完全部数据
        this.finished = true
      }
      // 对时间进行格式化处理
      res.data.data.results.forEach((obj) => {
        obj.pubdate = this.formatTime(obj.pubdate)
      })
      this.articleList = [...this.articleList, ...res.data.data.results]
      this.loading = false
    },
    // 加载更多
    async onLoad () {
      // 防止重复加载文章列表数据
      if (this.articleList.length > 0) {
        this.page++
        this.getSearchResult()
      }
    },
    // 文章详情,这个点击跳转也可以写在ArticleListItem中，若要考虑今后项目该组件的复用，就还是写在搜索结果组件中
    articleDetail (article_id) {
      console.log(123)
      this.$router.push({
        path: '/article_detail',
        query: {
          aid: article_id
        }
      })
    }
  },
  async created () {
    this.getSearchResult()
  }
}
</script>

<style lang="less" scoped>
.search-result-container {
  padding-top: 46px;
}

/deep/ .van-nav-bar {
  .van-icon {
    color: #fff;
  }
}
</style>
